var  basePath=$('#basePath').val();
var numone = 0;
var otherId='';
var othername = '';
var othertxt = '';
var _jc;
function dollor(id){ return document.getElementById(id) }
function trace(txt) {
	//console.log(txt);
	dollor("debug").innerHTML = txt + "<br>" + dollor("debug").innerHTML; 
}
function onmsg(txt) {
	if (txt.substring(0,2) == "\r\n") {//large string: help or stats
		txt = txt.replace(/\</g,"&lt;");
		txt = txt.replace(/\>/g,"&gt;");
		return trace(txt);
	}
	var json = JSON.parse(txt);
	if (!json) return trace(txt);
	var cmd = json.cmd, val = json.val;
	//console.log(val);
	if (cmd == "onactorstate"){					
		for (var i in val) {
			//大屏初始化
    			if(!dollor("iBigSmallActor").value){
				dollor("iBigSmallActor").value = i;
			}	
			var li = dollor(i);
			if (!li) {
				li = document.createElement('div');
				li.id = i;
				dollor("actorList").append(li);
			}
			li.style.margin = '0 0 10px 0';
			li.className = 'actor_count';
			var a = val[i];
			if(a.nick == '#SA'){//该成员进入，可以录制
				dollor("rec").style.display = "inline";
				continue;
			}else{
				otherId=i.split('@')[0].split(':')[1];
				othername=a.nick;
				othertxt=i.split(':')[1].split(']')[0];
				numone++;	
				//console.log(val);
				if(a.state=='3'){
					console.log('对方进入会议!');
					videoOC(othername,otherId);					
				}else if(a.state=='11'){
					//console.log('对方打开音频!');
					layer.closeAll();					
				}else if(a.state=='15'){
					//console.log('对方打开视频!');
					layer.closeAll();
					userMsg2(otherId);
				}				
			}
			var html = '';
			//判断状态
			if(a.state.toString(16) == 'a' || a.state.toString(16) == 'b' || a.state.toString(16) == 'e'){
				html = '<div title="麦克风开启" style="background:#8BC34A;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			}else if(a.state.toString(16) == '5' || a.state.toString(16) == '7' || a.state.toString(16) == 'd'){
				html = '<div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div title="摄像头开启" style="background:#03A9F4;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			}else if(a.state.toString(16) == 'f'){//摄像头开启
				html = '<div title="麦克风开启" style="background:#8BC34A;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div   title="摄像头开启" style="background:#03A9F4;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			}else{
				html = '<div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			}
			var checkId = "ch_" + i;
			var src = "";
			if($("#iMode").val() > 2){						
				src = basePath+"static/video/images/share.png";
			}else{
				src = basePath+"static/video/images/black.png";
			}
			if(a.subscribe == '1'){
				html += '<div style="width:60px;height:30px;margin-top:-3px;" class="pull-right"><img tag="' + i + '" class="share_btn" title="设为大屏" onclick="share_big(this)" src="' + src + '" alt=""><img id = "' + checkId + '" class="camara_open" onclick="subscribe('+"'"+i+"'"+');" title="订阅" src="'+basePath+'static/video/images/camara_open.png" alt=""></div>' + a.nick;
			}else{
				html += '<div style="width:60px;height:30px;margin-top:-3px;" class="pull-right"><img tag="' + checkId + '" class="share_btn" title="设为大屏" onclick="share_big(this)" src="' + src + '" alt=""><img id = "' + checkId + '" class="camara_close" onclick="subscribe('+"'"+i+"'"+');" title="订阅" src="'+basePath+'static/video/images/camara_close.png" alt=""></div>' + a.nick;
			}
			li.innerHTML = html;
			if($("#iMode").val() > 2 && i == $("#iBigSmallActor").val()){
				var idd = $(".actor_count").eq(1).attr('id');
				$("#iBigSmallActor").val(idd);
				$(".share_btn[tag='"+idd+"']").attr('src',basePath+'static/video/images/main_share.png');
			}
		}
		//console.log('对方进入会议');	
		if(numone==1){					
			videoOC(othername,otherId);
		}else{
			layer.closeAll();
		}
	}else if (cmd == "onactorleave"){
		console.log('对方退出会议');		
		disconnect();				
		for (var i=0,len=val.length;i<len;++i){
			dollor("actorList").removeChild(dollor(val[i]));			
		}
		var pos1 = val[0].indexOf(':');
		var pos2 = val[0].indexOf('@');
		var search = val[0].substring(pos1+1,pos2);
		if(search == '#SA'){
			dollor("rec").style.display = "none";
		}
		if($("#iMode").val() > 2 && val[0] == $("#iBigSmallActor").val()){
			var idd = $(".actor_count").eq(1).attr('id');
			$("#iBigSmallActor").val(idd);
			$(".share_btn[tag='"+idd+"']").attr('src',basePath+'static/video/images/main_share.png');
		}
	}else if (cmd == "onconfstate"){
		if(val.sharer == ""){//自己或他人退出共享屏幕
			dollor("share").onclick = share_start;
			dollor("share").src = basePath+'static/video/images/gongxiang1.png';
		}else if (val.sharer == dollor("toid").value){ // 自己开始共享屏幕			
			dollor("share").onclick = share_close;
			dollor("share").src = basePath+'static/video/images/gongxiang2.png';					
		}else if (val.sharer != dollor("toid").value){// 他人开始共享屏幕，自己被挤掉				
			dollor("share").onclick = share_start;
			dollor("share").src = basePath+'static/video/images/gongxiang1.png';
		}
	}else if (cmd == "onselfstate"){//自身状态发生改变时
		var html = '';
		//判断状态
		if(val.state.toString(16) == 'a' || val.state.toString(16) == 'b' || val.state.toString(16) == 'e'){
			html = '<div title="麦克风开启" style="background:#8BC34A;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			dollor("mic").src = basePath+'static/video/images/jingyin2.png';
		}else if(val.state.toString(16) == '5' || val.state.toString(16) == '7' || val.state.toString(16) == 'd'){
			html = '<div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div title="摄像头开启"  style="background:#03A9F4;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			dollor("mic").src = basePath+'static/video/images/jingyin1.png';
		}else if(val.state.toString(16) == 'f'){//摄像头开启
			html = '<div title="麦克风开启" style="background:#8BC34A;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div title="摄像头开启"  style="background:#03A9F4;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			dollor("mic").src = basePath+'static/video/images/jingyin2.png';
		}else{
			html = '<div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="background:;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div>';
			dollor("mic").src = basePath+'static/video/images/jingyin1.png';
		}
		if(val.state.toString(16) == '3' || val.state.toString(16) == 'b'){//摄像头被关闭
			html += '<div style="width:30px;height:30px;margin-top:-3px;" class="pull-right"><img id="video" title="开启摄像头" class="video_close" onclick="video_change()" src="'+basePath+'static/video/images/end.png" alt=""></div>ME';
		}else{
			html += '<div style="width:30px;height:30px;margin-top:-3px;" class="pull-right"><img id="video" title="关闭摄像头" class="video_open" onclick="video_change()" src="'+basePath+'static/video/images/start.png" alt=""></div>ME';
		}			
		dollor("selfstate").innerHTML = html;
	}else if (cmd == "onconfchat"){
		return trace(val.from + ": " + val.text);
	}else{
		return trace(cmd + (val ? " ok":" failed"));	
	}
	num = dollor("actorList").getElementsByClassName('actor_count').length;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
//创建会议start
function connect() {
	layer.msg('创建会议中...', {
		   icon: 16
		   ,shade: 0.01,
		   time:60000
	},function(){
		
	});
	dollor("error_msg").style.display = 'none';
	dollor("online_num").innerHTML = dollor("confid").value;
	dollor("voice").src = basePath+'static/video/images/ysq2.png';
	dollor("mic").src = basePath+'static/video/images/jingyin2.png';
	dollor("uid").disabled = dollor("connect").disabled = dollor("confid").disabled = dollor("confpwd").disabled = true;
	try {
		_jc = new WebRTC({
			'id':dollor("uid").value,
			'url':dollor("ws").value,
			'confProps': {
				"roomId":dollor("confid").value,
				"regionId":'0',
				"appKey":dollor("appKey").value,
				"accountName": dollor("uid").value,
				"mediaType":"1",
				"password": "1",
				"mtcConfPasswordKey":dollor("confpwd").value,
				"mtcConfQualityGradeKey":1,
				"mtcConfSecurityKey":0,
				"mtcConfCompositeModeKey":5,
				"mtcConfRoleKey":4,
				"mtcConfStateKey":3,
				"mtcConfCapacityKey":3
			}
		}, trace);
	} catch(error) {
		dollor("error_msg").style.display = 'block';
		dollor("connect").disabled = false;
		trace(error.name + ': ' + error.message + (error.number || ""));
		return;
	}
	_jc.onerror = function(error) {
		//console.log('错误对象');
		//console.log(error);
		dollor("connect").disabled = false;		
		dollor("error_msg").style.display = 'block';
		trace(error.name + ': ' + error.message + (error.number || ""));
		disconnect2();
	};
	_jc.oniceconnectionstatechange = function(state){				
		if(state == 'failed'){
			hangup();
			call();
			//console.log('呼叫1');
		}			
	}
	//第二步
	_jc.onopen = function(id, config){
		console.log('会议创建成功');
		layer.closeAll();
		setCookie("room", dollor("confid").value, 1);
		setCookie("uid", id);		
		dollor("uid").value = id;
		if (config) {
			dollor("toid").value = config.instanceId;
			dollor("confNum").value = config.confNum;
			dollor("toid").disabled = true;
			dollor("stun").value = config.iceServers[0].url;
			dollor("stunid").value = config.iceServers[0].username;
			dollor("stunpwd").value = config.iceServers[0].credential;
			_jc.send("@"+config.instanceId+"subscribe 0xf");
		}
		dollor("connect").disabled = dollor("sendmsg").disabled = false;
		dollor("actorList").innerHTML = '<div id="selfstate" class="actor_count" style="margin-bottom:10px"><div style="background:#8BC34A;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="background:#03A9F4;width:5px;height:5px;border-radius:50%;margin-top:10px;margin-right:8px" class="pull-left"></div><div style="width:30px;height:30px;margin-top:-3px;" class="pull-right"><img src="'+basePath+'static/video/images/start.png" alt=""></div>ME</div>';
	/*	call();
		console.log('呼叫2');*/
	}
	_jc.onclose = disconnect;
	_jc.onmessage = onmsg;
	_jc.oncall = function(peer) {				
		dollor("toid").value = peer;
		call();
		//console.log('呼叫3');
	}
	_jc.onhangup = hangup;
	_jc.onremovestream = function(stream, type) {
		able_share();				
		if (type == 'localvideo'){
			dollor("localVideo").srcObject = null;
		}else{
			if(dollor(stream.id)){
				dollor("remoteVideo").removeChild(dollor(stream.id));//将会议视频移除容器
			}
		}
	}
	_jc.onaddstream = function(stream, type) {				
		if (type == 'localvideo'){
			dollor("localVideo").srcObject = stream;
		}else if (type == 'peervideo' || type == 'peeraudio' || type == 'peershare') {
			var id = stream.id, view;
			if (type != 'peeraudio'){
				view=document.createElement('video');
				view.addEventListener('loadedmetadata', function() { trace(id + " remote " + this.videoWidth + "x" + this.videoHeight); });
			}
			else {
				view=document.createElement('audio');
			}
			view.id = id;
			view.srcObject = stream;
			view.autoplay = true;
			//将会议视频放入容器中,并且撑满容器
			dollor("remoteVideo").appendChild(view);
			dollor(id).style.width = '100%';
			dollor(id).style.height = '100%';
			$('#index').hide();
			$('.video').show();
			layer.closeAll();
		}
	}
}
//创建会议end
//打开音视频设备start
function call() {	
	if (dollor("toid").value == "") return trace("invalid toid");
	dollor("toid").disabled = dollor("stun").disabled = dollor("stunid").disabled = dollor("stunpwd").disabled = true;
	var constraints = navigator.mediaDevices.getUserMedia({ audio: true, video: true });
		constraints.then(function(stream) {
			_jc.call({'iceServers': [{
				'urls': [dollor("stun").value],
				'username':dollor("stunid").value,
				'credential':dollor("stunpwd").value
			}]}, stream, dollor("toid").value);
		});
		constraints.catch(function(err) {
			layer.alert('找不到音视频设备', {
				  skin: 'layui-layer-lan' //样式类名
				  ,closeBtn: 0
				  ,anim: 4 //动画类型
				}, function(){
					disconnect2();
				});
			/* alert('找不到音视频设备');
			 var constraints={ "audio": false, "video": false };
			_jc.call({'iceServers': [{
				'urls': [dollor("stun").value],
				'username':dollor("stunid").value,
				'credential':dollor("stunpwd").value
			}]}, constraints, dollor("toid").value);*/
		});
		var _width = 1280;
		var _height = 720;
		var _mode = $("#iMode").val();
		var _scsMode = $("#iScsMode").val();
		var _fps = 30;
		var _bigSmallActor = $("#iBigSmallActor").val();
		var txt = "@"+$("#toid").val()+"setmerge_i"+" "+_width+" "+_height+" "+_mode+" "+_scsMode+" "+_fps+" "+_bigSmallActor;
		_jc.send(txt, $("#toid").val());
}
//打开音视频设备end
//接受视频提示start
function videoOC(msg,id){
	userMsg(id,function(data){
		//start
		loadJsCss(basePath+"static/js/maxRemind_video/maxRemind.js",function(){
		   videodom(msg);		  	
		});
		//end
	});
};
function videodom(msg){
	var dom='<h4 style="text-align:center;margin-top: 20px;"><span style="color:#09C;">'+msg+'</span>发送视频请求</h4>';
	dom+='<div style="text-align:center;margin-top:40px;">';
	dom+='<button style="background-color:#09C;color: white;border:1px;border-radius:5px;width: 50px;height:25px;" onclick="videook();">接收</button>';
	dom+='<button style="border:1px;border-radius:5px;width: 50px;height:25px;margin-left: 10px;" onclick="videono();">拒绝</button></div>';
	MaxRemindFormat({path:basePath+"static/js/maxRemind_video/"});
	new MaxRemind({
		isTop:false,//提示框的显示的位置，false:在当前调用插件的窗口显示；true:在当前调用插件的顶层窗口显示。				
		msg: dom,
		order_remind:true,
		callback: function(obj){}
	});
	 $('.maxRemind').show();
}
function videono(){	
	disconnect2();
}
function videook(){	
	 layer.msg('用户正在支付费用中...', {
		   icon: 16
		   ,shade: 0.01,
		   time:300000
     });
	 //接收视频流2
	 call();
	//防止页面后退start
	 reloadBack();	
}
function videoOC2(msg,id){
	userMsg(id,function(data){
		if(msg=='患者'){
			msg='确定要接受患者的视频吗？';		
		}else{
			msg='确定要接受患者'+msg+'的视频吗？';
		}
		layer.confirm(msg, {
			  skin: 'layui-layer-lan',//样式类名
			  btn: ['取消','确认'] //按钮
			}, function(){
				//disothertxt();
				disconnect2();		       	   			       	 	   
			}, function(){
				//console.log(data);
				layer.closeAll();
				//打开加载1
				 layer.msg('用户正在支付费用中...', {
					   icon: 16
					   ,shade: 0.01,
					   time:300000
			     });
				 //接收视频流2
				 call();
				//防止页面后退start
				 reloadBack();	      		
			});
	});
};
//接受视频提示end
//防止页面后退start
function reloadBack(){
	history.pushState(null, null, document.URL);
	window.addEventListener('popstate', function () {
	    history.pushState(null, null, document.URL);
	});
	//刷新
	$(document).bind("keydown", function(e) {//文档绑定键盘按下事件
	    e = window.event || e;//解决浏览器兼容的问题   
	    var k = e.keyCode;
	    if((e.ctrlKey == true && k == 82) || (k == 116) || (e.ctrlKey == true && k == 116))
	    {				   
	        e.keyCode = 0;
	        e.returnValue = false;
	        e.cancelBubble = true;
	    }
	});
}
//防止页面刷新后退end	
//用户状态start
function  userMsg(customerId,callback){
	$.ajax({
		type: "POST",
		url: basePath+'physicianController/canReciveVideo.do',
		dataType:'json',
		data: {customerId:customerId},
		cache: false,
		success: function(data){
			//console.log(data);
			if (data.success){
				callback(data);							
			}else{
				 layer.closeAll();
				//disothertxt();
				console.log('状态异常');
				disconnect2();
			}
		},
		error: function(){
			
		}
	});
}
function  userMsg2(customerId){
	$.ajax({
		type: "POST",
		url: basePath+'physicianController/canReciveVideo.do',
		dataType:'json',
		data: {customerId:customerId},
		cache: false,
		success: function(data){
			//console.log(data);
			if (data.success){
				var otherContent=data.visitorInfo;
				if(otherContent.name){
					$('.othername').text(otherContent.name);
				}else{
					$('.othername').text('保密');
				}	
				if(otherContent.age){
					$('.otherage').text(otherContent.age+'岁');
				}else{
					$('.otherage').text('保密');
				}	
				if(otherContent.sex){
					$('.othersex').text(otherContent.sex);
				}else{
					$('.othersex').text('保密');
				}	
				if(otherContent.idcard){
					$('.otheridCarde').text(otherContent.idcard);
				}else{
					$('.otheridCarde').text('保密');
				}	
				if(otherContent.visitContent){
					$('.otherinformation').text(otherContent.visitContent);
				}else{
					$('.otherinformation').text('保密');
				}				
				$('.otherInfo').show();
			}else{
				//disothertxt();
				 layer.closeAll();
				console.log('状态异常');
				disconnect2();
			}
		},
		error: function(){
			
		}
	});
}
//用户状态end
//挂断start
function disconnect() {
	console.log('挂断');
	 $('.maxRemind').hide();
	 numone = 0;
	if (!_jc) return;		
	setCookie("room", "", -1);
	hangup();			
	_jc = _jc.close();
	dollor("sendmsg").disabled = true;
	dollor("ws").disabled = dollor("uid").disabled = dollor("connect").disabled = dollor("confid").disabled = dollor("confpwd").disabled = dollor("toid").disabled = false;
	if($('.video').css('display')=='none'){
		$('#index').show();
	    $('.video').hide();
	    layer.closeAll();
	    setTimeout(function(){
	   		 connect();
		 },6000); 
	}else{
		layer.msg('结束中...', {
			   icon: 16
			   ,shade: 0.01,
			   time:6000
		},function(){
			connect();
			$('#index').show();
		    $('.video').hide();
		    layer.closeAll();
		});
	}
}
//挂断end
function disconnect2() {
	console.log('挂断2');
	 $('.maxRemind').hide();
	numone = 0;	
	if (!_jc) return;		
	setCookie("room", "", -1);
	hangup();			
	_jc = _jc.close();
	dollor("sendmsg").disabled = true;
	dollor("ws").disabled = dollor("uid").disabled = dollor("connect").disabled = dollor("confid").disabled = dollor("confpwd").disabled = dollor("toid").disabled = false;
	$('#index').show();
    $('.video').hide();
    layer.closeAll();
    setTimeout(function(){
   		 connect();
	 },6000); 
}
function disothertxt(){
	console.log(othertxt);
	numone = 0;	
	//_jc.send({cmd:'kickuser',target:othertxt});
	 _jc.send("@"+$("toid").value+"kickuser "+othertxt, $("toid").value);
	 layer.closeAll();
}
//end==================================================================================================================================================
function share_big(obj){
	if(obj.tag == $("#iBigSmallActor").val()){				
		return false;
	}else{				
		$("#iBigSmallActor").val(obj.getAttribute('tag'));
		$(".share_btn").attr('src',basePath+'static/video/images/share.png');
		obj.src =basePath+'static/video/images/main_share.png';
	
		if ($("#toid").val() == "") return trace("invalid toid");
		if (!_jc) return;
		
		var _mode = $("#iMode").val();
		var _scsMode = $("#iScsMode").val();
		var _bigSmallActor = $("#iBigSmallActor").val();
				
		var txt = "@"+$("#toid").val()+"setmergemode_i"+" "+_mode+" "+_scsMode+" "+_bigSmallActor;				
		ret = _jc.send(txt, $("#toid").val());
	}
}		
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		var c_start, c_end;
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1 
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		} 
	}
	return ""
}
function checkCookie()
{
	var uid=getCookie('uid'), room=getCookie('room');
	if (uid != null && uid != "")
		dollor("uid").value = uid;
	else
		return;
	if (room!=null && room!="")
		dollor("confid").value = room;
	else
		return;
	connect();
}
function sendmsg() {
	if (dollor("toid").value == "") return trace("invalid toid");
	var txt = dollor("message").value;
	if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
	_jc.send(txt, dollor("toid").value);
	dollor("message").value = '';
	open_log()
}
function record(){		
	dollor("rec").src = basePath+'static/video/images/recording.png';
	var room = dollor("confNum").value;
	var txt = '{"cmd":"StartRecord","Video":true,"Storage":{"Protocol":"qiniu","AccessKey":"Th2jW_jP5VSk-wfdVMy5it1oK4iHa8pv8vBZMhbd","SecretKey":"Nh-_pgXrx9weiq8bkAtJPkrBlV3YP13U0Fx0fT-c","BucketName":"ajianzheng","FileKey":"' + room + '/' + dollor("uid").value + Date.parse(new Date()) + '.mp4","SplitFileSize":10240}}';
	var txt = '@sendtext ' + BASE64.encoder(txt) + ' [username:delivery_' + room + '@delivery.cloud.justalk.com]';
	if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
	_jc.send(txt, dollor("toid").value);
	dollor("rec").onclick = stop_record;
}

function stop_record(){
	dollor("rec").src = basePath+'static/video/images/rec.png';
	var room = dollor("confNum").value;
	var command = '{"cmd":"StopRecord"}';
	var txt = '@sendtext ' + BASE64.encoder(command) + ' [username:delivery_' + room + '@delivery.cloud.justalk.com]';
	if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
	_jc.send(txt, dollor("toid").value);
	dollor("rec").onclick = record;
}

function fullscreen(){
	var v = dollor("remoteVideo").getElementsByTagName('video');
	var element = v[0];
	if(element.requestFullScreen) {
		element.requestFullScreen();
	} else if(element.mozRequestFullScreen) {
		element.mozRequestFullScreen();
	} else if(element.webkitRequestFullScreen) {
		element.webkitRequestFullScreen();
	}
}
function hangup() {
	_jc.hangup();
	dollor("localVideo").srcObject = null;
	//将会议视频容器清空
	var v = dollor("remoteVideo").getElementsByTagName('video');
	if(v[0]){ dollor("remoteVideo").removeChild(v[0]); }
	dollor("stun").disabled = dollor("stunpwd").disabled = false;
	if (dollor("ws").value.indexOf("ws://")==0) dollor("toid").disabled = false;
}
function close_log(){
	dollor("log_img").onclick = dollor("log").onclick = open_log;
	dollor("debug_div").style.display = "none";
}
function open_log(){			
	dollor("log_img").onclick = dollor("log").onclick = close_log;
	dollor("debug_div").style.display = "block";
}
function share_start() {
	dollor("share").onclick = '';
	if (_jc.share) _jc.share(true);
}
function share_close() {
	if (_jc.share) _jc.share(false);
}
function able_share(){
	dollor("share").onclick = share_start;
}
function mic_close() {
	dollor("mic").src =basePath+"static/video/images/jingyin1.png";
	dollor("mic").onclick = mic_open;
	dollor("mic").className = "pointer mic_close";
	if(dollor("video").className == 'video_close'){//摄像头关闭状态
		_jc.mute(true,true);
	}else{//摄像头打开状态
		_jc.mute(true,false);
	}
	var txt = '@setstate 0x8 0x0';
	if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
	_jc.send(txt, dollor("toid").value);
}
function mic_open() {
	dollor("mic").src = basePath+"static/video/images/jingyin2.png";
	dollor("mic").onclick = mic_close;
	dollor("mic").className = "pointer mic_open";
	if(dollor("video").className == 'video_close'){//摄像头关闭状态
		_jc.mute(false,true);
	}else{//摄像头打开状态
		_jc.mute(false,false);
	}
	var txt = '@setstate 0x8 0x8';
	if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
	_jc.send(txt, dollor("toid").value);
}
function voice_close(){
	var v = dollor("remoteVideo").getElementsByTagName('video');
	v[0].muted = true;
	dollor("voice").src = basePath+'static/video/images/ysq1.png';
	dollor("voice").onclick = voice_open;
}
function voice_open(){
	var v = dollor("remoteVideo").getElementsByTagName('video');
	v[0].muted=false;
	dollor("voice").src = basePath+'static/video/images/ysq2.png';
	dollor("voice").onclick = voice_close;
}
function video_change(){
	if(dollor("video").className == 'video_close'){//摄像头关闭状态，准备打开
		dollor("video").src = basePath+'static/video/images/start.png';
		if(dollor("mic").className == "pointer mic_close"){//麦克风关闭状态
			_jc.mute(true,false);
		}else{//麦克风打开状态
			_jc.mute(false,false);
		}
		var txt = '@setstate 0x4 0x4';
		if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
		_jc.send(txt, dollor("toid").value);
		dollor("video").className = 'video_open';
	}else{//摄像头打开状态，准备关闭
		dollor("video").src = basePath+'static/video/images/end.png';
		if(dollor("mic").className == "pointer mic_close"){//麦克风关闭状态
			_jc.mute(true,true);
		}else{//麦克风打开状态
			_jc.mute(false,true);
		}
		var txt = '@setstate 0x4 0x0';
		if (txt.substring(0,1) == "@") txt = "@"+dollor("toid").value+txt.substring(1);
		_jc.send(txt, dollor("toid").value);
		dollor("video").className = 'video_close';
	}
}
function subscribe(uri){
	var checkId = 'ch_' + uri;
	var state = dollor(checkId).className == 'camara_close' ? 1 : 0;
	dollor(checkId).src = dollor(checkId).className == 'camara_open' ? ''+basePath+'static/video/images/camara_close.png' : ''+basePath+'static/video/images/camara_open.png';
	dollor(checkId).className = dollor(checkId).className == 'camara_close' ? 'camara_open' : 'camara_close';
	var ret;
	if (dollor("toid").value == "") return trace("invalid toid");
	var txt = "@"+dollor("toid").value+"vsubscribe"+" "+uri+" "+state;

	ret = _jc.send(txt, dollor("toid").value);
	if(ret == 0)
		return 1;

	return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
dollor("localVideo").addEventListener('loadedmetadata', function() { trace("local " + this.videoWidth + "x" + this.videoHeight); });
window.unload = disconnect2;
window.onload = checkCookie();